# coding:utf-8
import socket

"""
python服务器：
https://www.cnblogs.com/chaojiyingxiong/p/9822444.html
decode英文意思是 解码，encode英文原意 编码
字符串在Python内部的表示是unicode编码，因此，在做编码转换时，通常需要以unicode作为中间编码， 即先将其他编码的字符串解码（decode）成unicode，再从unicode编码（encode）成另一种编码。
"""


# log代替print
def log(*args, **kwargs):
    print('log', *args, **kwargs)


def route_index():
    """
    主页的处理函数,返回主页的响应
    """
    header = 'HTTP/1.x 200 OK\r\nContent-Type:text/html\r\n'
    body = '<h1>Hello World</h1><img src="doge.gif"/>'
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


def route_img():
    """
    图片的处理函数,读取图片并生成响应返回
    """
    with open('doge.gif', 'rb') as f:
        header = b'HTTP/1.x 200 OK\r\nContent-Type:image/gif\r\n\r\n'
        img = header + f.read()
        return img


# 不要用数字作为字典的key
# 但是在http 协议中 code 都是数字似乎方便,打破了这个原则
def error(code=404):
    e = {
        404: b'HTTP/1.x 404 NOT found\r\n\r\n<h1>NOT FOUND</h1>',
    }
    return e.get(code, b'')


def response_for_path(path):
    r = {
        '/': route_index,
        '/doge.gif': route_img,
    }
    response = r.get(path, error)
    return response()


def run(host='', port=3000):
    """
    启动服务器
    """
    with socket.socket() as s:
        s.bind(host, port)
        while True:
            s.listen(5)
            connection, address = s.accept()
            request = connection.recv(1024)
            request = request.decode('utf-8')
            log('ip and request,{}\n{}'.format(address, request))
            try:
                path = request.split()[1]
                response = response_for_path(path)
                connection.sendall(response)
            except Exception as e:
                log('error', e)
            connection.close()


if __name__ == '__main__':
    # 生成配置并且运行程序
    config = dict(
        host='',
        port=3000,
    )
    run(**config)
